# -*- coding: utf-8 -*-
import os
from configparser import ConfigParser


class version:
    def __init__(self):
        self.res = {}
        self.load_config()

    def load_config(self):
        cfgName = 'config/version.cfg'
        # print(cfgName)
        if os.path.exists(cfgName):
            config_parser = ConfigParser()
            config_parser.read(cfgName, encoding='utf8')
            cfgs = config_parser.sections()
            ll = []
            for c in cfgs:
                config = config_parser[c]
                rr = {}
                if c[:6] == 'camera':
                    for cfg in config:
                        rr[cfg] = config[cfg]
                    ll.append(rr)
                    self.res[c[:6]] = ll
                else:
                    for cfg in config:
                        rr[cfg] = config[cfg]
                        self.res[c] = rr
            # print(self.res)

    def add_cfg(self, section, name, value):
        # 创建ConfigParser对象
        config = ConfigParser()
        cfgName = 'config/version.cfg'
        # 读取现有的配置文件
        config.read(cfgName, encoding='utf8')
        # 检查section是否存在，如果不存在则创建
        if not config.has_section(section):
            config.add_section(section)
        # 在新的section下添加键值对
        config.set(section, name, value)
        # 打开配置文件并写入更改
        with open(cfgName, 'w') as configfile:
            config.write(configfile)
